//
//  AddModuleViewController.m
//  ZhuoxinAgriculture
//
//  Created by stone on 16/11/13.
//  Copyright © 2016年 KKING. All rights reserved.
//
#import "ZXLoginViewController.h"
#import "ConstValues.h"
#import "AddModuleViewController.h"
#import "AddModuleAlreadyAddedCell.h"
#import "AddModuleNotAddedCell.h"
#import "AddModuleHeaderView.h"
#define HexRGBA(rgbValue, al) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16)) / 255.0 green:((float)((rgbValue & 0xFF00) >> 8)) / 255.0 blue:((float)(rgbValue & 0xFF)) / 255.0 alpha:al]

#define HexRGB(rgbValue) HexRGBA(rgbValue, 1.0)
@interface AddModuleViewController ()<UITableViewDataSource,UITableViewDelegate>
/** tableView */
@property (nonatomic,weak) UITableView * tableView;
/** sectionCount */
@property (nonatomic, assign) NSInteger sectionCount;

/** alreadyAdded */
@property (nonatomic,strong) NSMutableArray<DBModel *> * alreadyAdded;
/** notAdded */
@property (nonatomic,strong) NSMutableArray<DBModel *> * notAdded;
@end

@implementation AddModuleViewController
-(void)setModels:(NSMutableArray<DBModel *> *)models{
    _models = models;
    
    NSMutableArray<DBModel *> * alreadyAdded = @[].mutableCopy;
    self.alreadyAdded = alreadyAdded;
    NSMutableArray<DBModel *> * notAdded = @[].mutableCopy;
    self.notAdded = notAdded;
    [models enumerateObjectsUsingBlock:^(DBModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isAddtion) {
            [alreadyAdded addObject:obj];
        }else{
            [notAdded addObject:obj];
        }
    }];
//    if (alreadyAdded.count>0) {
//         self.sectionCount = 2;
//    }else{
//         self.sectionCount = 1;
//    }
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithString:@"F579F7"] forBarMetrics:UIBarMetricsDefault];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view, typically from a nib.
    self.navigationItem.title = @"添加模块";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(doneButtonClick:)];
    CGFloat red = 179;
    CGFloat green = 78;
    CGFloat blue = 179;
    UIColor * color = [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1.0];

    [self.navigationItem.rightBarButtonItem setTintColor:color];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    CGRect frame = CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height - 64);
    UITableView * tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStyleGrouped];
    self.tableView = tableView;
    red = 245;
    green = 245;
    blue = 245;
    color = [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1.0];
    tableView.backgroundColor = color;
    //    if (tableView.contentSize.height >= [UIScreen mainScreen].bounds.size.height - 64) {
    //        tableView.scrollEnabled = NO;
    //    }else{
    //        tableView.scrollEnabled = YES;
    //    }
    [self setupInit:tableView];
    
    [self.view addSubview:tableView];
    
    [self addObserver];
    [self addRequest];
}
- (void)doneButtonClick:(UIBarButtonItem *)sender
{
    NSMutableArray * arrM = [NSMutableArray array];
    NSLog(@"%@ | %s",self.class,__func__);
    if (self.alreadyAdded.count>0) {
        [self.alreadyAdded enumerateObjectsUsingBlock:^(DBModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [arrM addObject:obj];
        }];
    }
    if (self.notAdded.count>0) {
        [self.notAdded enumerateObjectsUsingBlock:^(DBModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [arrM addObject:obj];
        }];
    }
    NSLog(@"arrM = %@",arrM);
    self.models = arrM;

    NSString * fileName = [NSString stringWithFormat:@"addmodulelist%@.plist",[ZXLoginViewController getPhoneNumber]];
    // NSString * filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
    
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *plistPath1 = [paths objectAtIndex:0];
    
    NSString *filename=[plistPath1 stringByAppendingPathComponent:fileName];
    NSLog(@"filename = %@",filename);
    NSMutableArray * arrMM = [NSMutableArray array];
    
    [self.models enumerateObjectsUsingBlock:^(DBModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       
        NSMutableDictionary * dictM = [NSMutableDictionary dictionary];
        dictM[@"title"] = obj.title;
        dictM[@"titleColorString"] = obj.titleColorString;
        dictM[@"subTitle"] = obj.subTitle;
        dictM[@"title"] = obj.title;
        dictM[@"iconName"] = obj.iconName;
        dictM[@"addition"] = @(obj.addition);
        [arrMM addObject:dictM];
    }];
    
    [arrMM writeToFile:filename atomically:YES];
    
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - <addRequest>
- (void)addRequest {
    // addRequest
}
#pragma mark - <addObserver>
- (void)addObserver {
    // addObserver
}
- (void)dealloc {
    NSLog(@"%@ %s %@",[self class], __func__ , @"im dying");
}

- (void)setupInit:(UITableView *)tableView {
    tableView.delegate = self;
    tableView.dataSource = self;
    
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self setHeights:tableView];
    [self registerNib:tableView];
    [self registerClass:tableView];
}
#pragma mark - <Register>
/** registerNib */
- (void)registerNib:(UITableView *)tableView {
    //    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([SNTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([SNTableViewCell class])];
}
/** registerClass */
- (void)registerClass:(UITableView *)tableView {
    //    [tableView registerClass:[SNTableViewCell class] forCellReuseIdentifier:NSStringFromClass([SNTableViewCell class])];
    [tableView registerClass:[AddModuleAlreadyAddedCell class] forCellReuseIdentifier:NSStringFromClass([AddModuleAlreadyAddedCell class])];
    [tableView registerClass:[AddModuleNotAddedCell class] forCellReuseIdentifier:NSStringFromClass([AddModuleNotAddedCell class])];
        [tableView registerClass:[AddModuleHeaderView class] forHeaderFooterViewReuseIdentifier:NSStringFromClass([AddModuleHeaderView class])];
}
#pragma mark - <SetHeights>
/** setHeights */
- (void)setHeights:(UITableView *)tableView {
    
    /** header */
    //    tableView.sectionHeaderHeight = 44;
     tableView.estimatedSectionHeaderHeight = 65;
     tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
    /** cell */
    //  tableView.estimatedRowHeight = 105 * 2 + 10;
    //    tableView.rowHeight = kItemHeight * 2 + 10;
    /** footer */
    tableView.sectionFooterHeight = 0.001;
    // tableView.estimatedSectionFooterHeight = 100;
    // tableView.sectionFooterHeight = UITableViewAutomaticDimension;
}

#pragma mark - <UITableViewDataSource>
/** 组数 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}
/** 行数 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
//MARK: -
//MARK: - cell
/** cell */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell * cellTemp= nil;
    NSLog(@"indexPath.row = %ld",indexPath.row);
    switch (indexPath.section) {
            case 0:
        {
            AddModuleAlreadyAddedCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AddModuleAlreadyAddedCell class])];
            cell.contentView.backgroundColor = indexPath.section % 2 == 0 ?cell.contentView.backgroundColor = [UIColor colorWithRed:76 / 255.0 green:165 / 255.0 blue:146 / 255.0 alpha:1.0]:[UIColor colorWithRed:152 / 255.0 green:208 / 255.0 blue:201 / 255.0 alpha:1.0];
            
            cell.alreadyAdded = self.alreadyAdded;
            cell.notAdded = self.notAdded;
            cellTemp = cell;
        }
            break;
            
            case 1:
        {
            AddModuleNotAddedCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AddModuleNotAddedCell class])];
            cell.contentView.backgroundColor = indexPath.section % 2 == 0 ?cell.contentView.backgroundColor = [UIColor colorWithRed:76 / 255.0 green:165 / 255.0 blue:146 / 255.0 alpha:1.0]:[UIColor colorWithRed:152 / 255.0 green:208 / 255.0 blue:201 / 255.0 alpha:1.0];
            cell.alreadyAdded = self.alreadyAdded;
            cell.notAdded = self.notAdded;
            cellTemp = cell;
        }
            break;
        default:
            
            break;
    }
    
    return cellTemp;
    
}

#pragma mark - <UITableViewDelegate>
/** 自定义section header */
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    AddModuleHeaderView * headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass([AddModuleHeaderView class])];
    CGFloat red = 245;
    CGFloat green = 245;
    CGFloat blue = 245;
    UIColor * color = [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1.0];

    headerView.contentView.backgroundColor = color;
    
    //    SNHeaderView * headerView = [SNHeaderView headerViewWithTableView:tableView];
    
    switch (section) {
            case 0:
            headerView.titleLabel.text = @"已添加";
            if (self.sectionCount == 1) {
                headerView.titleLabel.text = @"未添加";
            }
            break;
            
            case 1:
            headerView.titleLabel.text = @"未添加";
            break;
        default:
            break;
    }
    
    return headerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return kItemHeight * 2 + 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return -1;
}
/** 选中一行 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%s", __func__);
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
/** 取消 选中 */
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(3_0) {
    NSLog(@"%s", __func__);
}
/** 可编辑 */
//- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return YES;
//}
/** 删除样式 */
//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return UITableViewCellEditingStyleDelete;
//}
/** 删除当前行 */
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
//
//    if (editingStyle == UITableViewCellEditingStyleDelete) {
//
//        [self.models removeObjectAtIndex:indexPath.row];
//
//        [tableView deleteRowsAtIndexPaths:@[ indexPath ] withRowAnimation:UITableViewRowAnimationLeft];
//}
//sn_note:=========  ============================ stone 🐳 ===========/
/** 16进制(字符串形式) 返回 图片 */
- (UIImage *)imageWithString:(NSString *)string {
    
    return [self imageWithColor:[self colorWithString:string]];
}
/** 16进制返回颜色 */
- (UIColor *)colorWithString:(NSString *)string {
    CGFloat alpha = 0.7f;
    NSNumber * red = @0.0;
    NSNumber * green = @0.0;
    NSNumber * blue = @0.0;
    
    NSMutableArray<NSNumber *> * colors = [NSMutableArray arrayWithArray:@[ red, green, blue ]];
    
    unsigned hexComponent;
    NSString * colorString = [string uppercaseString];
    NSLog(@"%ld", colors.count);
    for (int i = 0; i < colors.count; i++) {
        NSString * substring = [colorString substringWithRange:NSMakeRange(i * 2, 2)];
        
        [[NSScanner scannerWithString:substring] scanHexInt:&hexComponent];
        
        NSNumber * temp = colors[i];
        temp = @(hexComponent / 255.0);
        colors[i] = temp;
    }
    
    return [UIColor colorWithRed:[colors[0] floatValue] green:[colors[1] floatValue] blue:[colors[2] floatValue] alpha:alpha];
}
/** 颜色 返回 图片 */
- (UIImage *)imageWithColor:(UIColor *)color {
    
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}
@end
